﻿using AutoMapper;
using Chat_IService;
using Chat_Model;
using Chat_Model.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Chat_WebApi.Controllers.v1
{
    [Route("/api/v1/[controller]")]
    [ApiController]
    //[Authorize]
    public class GroupController : BaseController
    {
        private readonly ILarUsersService _larUsersService;
        private readonly ILarUsersFriendsService _larUsersFriendsService;
        private readonly IMapper _mapper;
        private readonly ILarTalkListService _larTalkListService;
        private readonly IHubContext<SignalRHub> _hubContext;
        private readonly IMemoryCache _cache;
        private readonly ILarTalkRecordsService _larTalkRecordsService;
        private readonly ILarGroupService _larGroupService;
        private readonly ILarGroupMemberService _larGroupMemberService;

        public GroupController(
            IHubContext<SignalRHub> hubClients,
            IMemoryCache memoryCache,
            ILarUsersService larUsersService,
            IMapper mapper,
            ILarTalkListService larTalkListService,
            ILarTalkRecordsService larTalkRecordsService,
            ILarUsersFriendsService larUsersFriendsService,
            ILarGroupService larGroupService,
       ILarGroupMemberService larGroupMemberService

            )
        {
            this._larUsersService = larUsersService;
            this._mapper = mapper;
            this._larTalkListService = larTalkListService;
            this._hubContext = hubClients;
            this._cache = memoryCache;
            this._larTalkRecordsService = larTalkRecordsService;
            this._larUsersFriendsService = larUsersFriendsService;
            this._larGroupService = larGroupService;
            this._larGroupMemberService = larGroupMemberService;
        }
        /// <summary>
        ///  群组列表 
        /// </summary>
        [HttpGet("list")]
        public async Task<MessageModel<object>> List()
        {
            int uid = this._larUsersService.GetUserId();
            List<object> retlist = new List<object>();
            var list = this._larGroupMemberService.GetList(x => x.UserId == uid && x.IsQuit == 0 && x.IsQuit == 0);
            list.ForEach(item =>
            {
                retlist.Add(new
                {
                    group_name = this._larGroupService.GetById(item.GroupId).GroupName,
                    group_id = item.GroupId,
                });
            });

            return this.Success(retlist);
        }
        /// <summary>
        ///  群组成员列表
        /// </summary>
        [HttpGet("members")]
        public async Task<MessageModel<object>> Members([FromQuery] int group_id)
        {
            return this.Success();
        }
        /// <summary>
        ///  群组详细信息
        /// </summary>
        [HttpGet("detail")]
        public async Task<MessageModel<object>> Detail([FromQuery] int group_id)
        {
            return this.Success();
        }
        /// <summary>
        ///  创建群组
        /// </summary>
        [HttpPost("create")]
        public async Task<MessageModel<object>> Create([FromBody] GroupCreateParam param)
        {
            LarUsers larUsers = await this._larUsersService.GetUserInfoAsync();
            int gid = this._larGroupService.InsertReturnIdentity(new LarGroup()
            {
                CreatorId = larUsers.Id,
                GroupName = param.Group_Name,
                Profile = param.Group_Profile,
                Avatar = param.Group_Avatar,
            });
            if (gid > 0)
            {
                List<int> menList = (from item in param.Group_Avatar.Split(',')
                                     select item.ObjToInt()).ToList();
                List<LarUsers> users = await this._larUsersService.GetListAsync(x => menList.Contains(x.Id));

                List<Chat_Model.LarGroupMember> larGroupMembersList = new List<LarGroupMember>();
                users.ForEach(item =>
                {
                    larGroupMembersList.Add(new LarGroupMember
                    {
                        GroupId = gid,
                        UserId = item.Id,
                        Leader = 0,
                        UserCard = item.Nickname,
                    });
                });
                larGroupMembersList.Add(new LarGroupMember
                {
                    GroupId = gid,
                    UserId = larUsers.Id,
                    Leader = 2,
                    UserCard = larUsers.Nickname,
                });
                this._larGroupMemberService.InsertRange(larGroupMembersList);
                return this.Success(new
                {
                    Group_id = gid,
                    Name = param.Group_Name,
                    Profile = param.Group_Profile,
                    Avatar = param.Group_Avatar,
                });
            }
            else
                return this.Error();
        }
        /// <summary>
        ///  修改群组
        /// </summary>
        /// <returns><placeholder>A <see cref="Task"/> representing the asynchronous operation.</placeholder></returns>
        [HttpGet("edit")]
        public async Task<MessageModel<object>> Edit()
        {
            return this.Success();
        }
        /// <summary>
        ///  退出群组 
        /// </summary>
        [HttpPost("secede")]
        public async Task<MessageModel<object>> Secede([FromBody] GroupBaseParam param)
        {
            int group_id = param.Group_Id.ObjToInt();
            if (group_id == 0) return this.Error();
            int uid = this._larUsersService.GetUserId();
            LarGroup larGroupModel = await this._larGroupService.GetSingleAsync(x => x.Id == group_id);
            LarGroupMember larGroupMemberModel = await this._larGroupMemberService.GetSingleAsync(x => x.UserId == uid && x.GroupId == group_id);
            larGroupMemberModel.IsQuit = 1;
            larGroupMemberModel.DeletedAt = System.DateTime.Now;
            if (this._larGroupMemberService.Update(larGroupMemberModel))
                return this.Success();
            else
                return this.Error();
        }
        /// <summary>
        ///  解散群组
        /// </summary>
        /// <returns><placeholder>A <see cref="Task"/> representing the asynchronous operation.</placeholder></returns>
        [HttpPost("dismiss")]
        public async Task<MessageModel<object>> Dismiss([FromBody] GroupBaseParam group_id)
        {
            return this.Success();
        }
        /// <summary>
        ///  邀请加入群组
        /// </summary>
        [HttpPost("invite")]
        public async Task<MessageModel<object>> Invite([FromBody] int group_id)
        {
            return this.Success();
        }

        /// <summary>
        ///  移除指定成员
        /// </summary>
        [HttpPost("remove-members")]
        public async Task<MessageModel<object>> RemoveMembers([FromBody] int group_id)
        {
            return this.Success();
        }

        /// <summary>
        ///  设置群组名片
        /// </summary>
        [HttpPost("set-group-card")]
        public async Task<MessageModel<object>> setGroupCard([FromBody] int group_id)
        {
            return this.Success();
        }

        /// <summary>
        ///  获取可邀请加入群组的联系人列表
        /// </summary>
        [HttpGet("invite-friends")]
        public async Task<MessageModel<object>> InviteFriends([FromQuery] GroupBaseParam group_id)
        {
            int uid = this._larUsersService.GetUserId();
            var list = await this._larUsersFriendsService.GetContactsList(uid);
            return this.Success(list);
        }

        /// <summary>
        ///  获取群公告列表
        /// </summary>
        [HttpGet("notices")]
        public async Task<MessageModel<object>> Notices([FromQuery] GroupBaseParam group_id)
        {
            return this.Success();
        }
        /// <summary>
        ///  创建/编辑群公告
        /// </summary>
        [HttpPost("edit-notice")]
        public async Task<MessageModel<object>> EditNotice([FromBody] GroupEditNoticeParam group_id)
        {
            return this.Success();
        }

        /// <summary>
        ///  删除群公告
        /// </summary>
        [HttpPost("delete-notice")]
        public async Task<MessageModel<object>> DeleteNotice([FromBody] GroupDeleteNoticeParam group_id)
        {
            return this.Success();
        }
    }
}
